import { useAPIUtils } from "@/components/APIUtilsProvider";
import PageLayout from "@/components/PageLayout";
import { DragDropContext, Draggable, Droppable } from "@hello-pangea/dnd";
import {
  ActionIcon,
  Box,
  Button,
  Center,
  CloseButton,
  Container,
  Grid,
  Group,
  Select,
  TextInput,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { IconGripVertical, IconPlus } from "@tabler/icons-react";
import { useState } from "react";

export default function DictionaryMaintainence() {
  const [dictName, setDictName] = useState(null);

  return (
    <PageLayout title={"字典维护"}>
      <Grid w={"96%"}>
        <Grid.Col span={2}>
          <Group justify="flex-end">
            <Select
              placeholder="请选择要编辑的字典"
              value={dictName}
              onChange={setDictName}
              data={[{ value: "protocol_type", label: "协议类型字典" }]}
            />
          </Group>
        </Grid.Col>
        <Grid.Col span={6}>{dictName && <Edit dictName={dictName} />}</Grid.Col>
      </Grid>
      <Container w="600"></Container>
    </PageLayout>
  );
}

function Edit({ dictName }) {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const dictQuery = tanstackQuery(`/api/dictionaries/${dictName}`);

  if (!dictQuery.data) {
    return <></>;
  }

  const items = [];

  for (let k in dictQuery.data) {
    items.push({ key: k, text: dictQuery.data[k].text });
  }

  return <EditForm items={items} dictName={dictName} key={dictName} />;
}

function EditForm({ items, dictName }) {
  const form = useForm({
    initialValues: {
      items: [...items],
    },
    validate: {},
  });

  const { restPUT, tanstackInvalidate } = useAPIUtils();

  const maintain = async (formValues) => {
    let values = {};
    formValues.items.forEach((i) => (values[i.key] = { text: i.text }));
    await restPUT(`/api/admin/dictionaries/${dictName}`, values);
    tanstackInvalidate(`/api/dictionaries/${dictName}`);
  };

  const fields = form.values.items.map((_, index) => (
    <Draggable key={index} index={index} draggableId={index.toString()}>
      {(provided) => (
        <Group
          ref={provided.innerRef}
          mt="xs"
          {...provided.draggableProps}
          justify="end"
        >
          <Center {...provided.dragHandleProps}>
            <IconGripVertical size="1.2rem" />
          </Center>
          <TextInput
            w={"220"}
            placeholder="键名"
            {...form.getInputProps(`items.${index}.key`)}
          />

          <TextInput
            w={"220"}
            placeholder="文本"
            {...form.getInputProps(`items.${index}.text`)}
          />

          <CloseButton onClick={() => form.removeListItem("items", index)} />
        </Group>
      )}
    </Draggable>
  ));

  return (
    <form onSubmit={form.onSubmit(maintain)} key={dictName}>
      <Group justify="flex-end" mb="lg">
        <Button variant="light" onClick={form.reset}>
          重置
        </Button>
        <Button type="submit">保存</Button>
      </Group>

      <Box maw={"100%"} mx="auto">
        <DragDropContext
          onDragEnd={({ destination, source }) =>
            destination?.index !== undefined &&
            form.reorderListItem("items", {
              from: source.index,
              to: destination.index,
            })
          }
        >
          <Droppable droppableId="dnd-list" direction="vertical">
            {(provided) => (
              <div {...provided.droppableProps} ref={provided.innerRef}>
                {fields}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>
      </Box>
      <Group justify="flex-end" mt="md">
        <ActionIcon
          size="sm"
          variant="light"
          aria-label="add"
          onClick={() =>
            form.insertListItem("items", {
              item: "",
              quantity: null,
              unit: "",
              price: null,
            })
          }
        >
          <IconPlus style={{ width: "70%", height: "70%" }} stroke={1.5} />
        </ActionIcon>
      </Group>
    </form>
  );
}
